package com.liqi.web.controller.device;

import com.liqi.common.annotation.Log;
import com.liqi.common.constant.UserConstants;
import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.AjaxResult;
import com.liqi.common.core.domain.R;
import com.liqi.common.core.page.TableDataInfo;
import com.liqi.common.enums.BusinessType;
import com.liqi.common.utils.DateUtils;
import com.liqi.common.utils.StringUtils;
import com.liqi.common.utils.excel.ExcelUtils;
import com.liqi.common.utils.poi.ExcelUtil;
import com.liqi.common.utils.uuid.GenerateCodeUtils;
import com.liqi.device.domain.DvDevice;
import com.liqi.device.domain.DvDeviceModule;
import com.liqi.device.domain.DvDrive;
import com.liqi.device.domain.DvModule;
import com.liqi.device.service.IDvDeviceModuleService;
import com.liqi.device.service.IDvDeviceService;
import com.liqi.device.service.IDvDriveService;
import com.liqi.device.service.IDvModuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 模块Controller
 *
 * @author zhongping
 * @date 2022-02-14
 */
@Api(tags = "设备管理")
@RestController
@RequestMapping("/device/module")
public class DvModuleController extends BaseController
{
    @Autowired
    private IDvModuleService dvModuleService;

    @Autowired
    private IDvDeviceModuleService dvDeviceModuleService;

    @Autowired
    private IDvDeviceService dvDeviceService;

    @Autowired
    private IDvDriveService dvDriveService;

    /**
     * 查询模块列表
     */
    @ApiOperation("查询模块列表")
    @PreAuthorize("@ss.hasPermi('device:module:list')")
    @GetMapping("/list")
    public TableDataInfo list(DvModule dvModule)
    {
        startPage();
        List<DvModule> list = dvModuleService.selectDvModuleList(dvModule);
        return getDataTable(list);
    }

    /**
     * 导出模块列表
     */
    @ApiOperation("导出模块")
    @PreAuthorize("@ss.hasPermi('device:module:export')")
    @Log(title = "模块", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DvModule dvModule)
    {
            if(dvModule.getExportBlank()==1){
                List<DvModule> modules=new ArrayList<>();
                dvModule=new DvModule();
                modules.add(dvModule);
                ExcelUtil<DvModule> util = new ExcelUtil<DvModule>(DvModule.class);
                util.exportExcel(response, modules , "模块数据");
            }else {
                List<DvModule> list = dvModuleService.selectDvModuleList(dvModule);

                ExcelUtil<DvModule> util = new ExcelUtil<DvModule>(DvModule.class);
                util.exportExcel(response, list, "模块数据");
            }
    }

    /**
     * 获取模块详细信息
     */
    @PreAuthorize("@ss.hasPermi('device:module:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(dvModuleService.selectDvModuleById(id));
    }

    /**
     * 新增模块
     */
    @ApiOperation("新增模块")
    @PreAuthorize("@ss.hasPermi('device:module:add')")
    @Log(title = "模块", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DvModule dvModule)
    {
        dvModule.setCode(GenerateCodeUtils.getSequnce());
    	 if (UserConstants.NOT_UNIQUE.equals(dvModuleService.checkCodeUnique(dvModule)))
         {
             return AjaxResult.error("新增模块" + dvModule.getName() + "'失败，编码已存在");
         }
    	 dvModule.setCreateBy(getUsername());
    	 dvModule.setCreateTime(DateUtils.getNowDate());
         dvModule.setCreateUserId(getUserId().toString());
         dvModule.setDeptId(getDeptId().toString());
         dvModule.setUpdateBy(getUsername());
         dvModule.setUpdateTime(DateUtils.getNowDate());
    	 return toAjax(dvModuleService.insertDvModule(dvModule));
    }

    /**
     * 修改模块
     */
    @ApiOperation("修改模块")
    @PreAuthorize("@ss.hasPermi('device:module:edit')")
    @Log(title = "模块", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DvModule dvModule)
    {
    	if (UserConstants.NOT_UNIQUE.equals(dvModuleService.checkCodeUnique(dvModule)))
        {
            return AjaxResult.error("修改模块" + dvModule.getName() + "'失败，编码已存在");
        }
        dvModule.setDeptId(getDeptId().toString());
        dvModule.setUpdateBy(getUsername());
    	dvModule.setUpdateTime(DateUtils.getNowDate());
        return toAjax(dvModuleService.updateDvModule(dvModule));
    }

    /**
     * 删除模块
     */
    @ApiOperation("删除模块")
    @PreAuthorize("@ss.hasPermi('device:module:remove')")
    @Log(title = "模块", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        List<DvModule> removeList = new ArrayList<>();
        List<DvDevice> dvDevices = new ArrayList<DvDevice>();
        for (Long id : ids) {
            DvModule dvModule = dvModuleService.selectDvModuleById(id); //查询模块
            List<DvDeviceModule> dvDeviceModules = dvDeviceModuleService.selectDvDeviceModuleByModuleCode(dvModule.getCode()); //查询设备-模块关联(根据moduleCode)
            for (DvDeviceModule dvDeviceModule : dvDeviceModules) {
                DvDevice dvDevice = dvDeviceService.selectDvDeviceByCode(dvDeviceModule.getDeviceCode()); //通过系统自编型号编码 查询设备
                if (dvDevice != null && dvDevice.getStatus() == 0) {
                    dvDevice.setDeleteModelCode(dvModule.getCode()); //模块编码
                    dvDevice.setDeleteModelName(dvModule.getName()); //模块名称
                    dvDevices.add(dvDevice);
                }
            }
            dvModule.setUpdateBy(getUsername());
            dvModule.setUpdateTime(DateUtils.getNowDate());
            dvModule.setStatus(1);
            removeList.add(dvModule);
        }
        if (dvDevices.size() != 0) {
            return AjaxResult.error("模块被设备引用,需要将模块与指定设备进行解绑",dvDevices);
        }
        int i = 0;
        for (DvModule dvModule : removeList) {
            i = dvModuleService.updateDvModule(dvModule);
        }
        return toAjax(i);
    }



    @ApiOperation("导入模块excel")
    @PostMapping("/import")
    public R importUser(@RequestPart("file") MultipartFile file) throws Exception {

        List<DvModule> dvModules = ExcelUtils.readMultipartFile(file, DvModule.class);
        String message ;
        if(dvModules.size()==0){
            return  R.ok("传入的非模板文件,请下载模板文件在进行导入");
        }
        message=   dvModuleService.importModule(dvModules);
        if(StringUtils.isBlank(message)){
            message="上传成功！";
        }
        return R.ok(message);
    }

}
